package com.portal.encryption.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 存储密码加密/验证工具类
 *
 * @author Amadeus
 * @date 2025/05/13
 */
public class CryptUtil {

    private static final BCryptPasswordEncoder ENCODER = new BCryptPasswordEncoder(12);

    /**
     * encode:(加密密码)
     *
     * @param password 密码 返回包含盐值的完整哈希字符串
     * @return {@link String }
     */
    public static String encode(String password) {
        return ENCODER.encode(password);
    }

    /**
     * 验证密码
     *
     * @param password   密码
     * @param storedHash 存储哈希
     * @return boolean
     */
    public static boolean verifyPassword(String password, String storedHash) {
        return ENCODER.matches(password, storedHash);
    }

    public static void main(String[] args) {
        // 创建密码服务实例

        // 测试用例1: 基本密码验证
        String password1 = "MySecurePassword123";
        String hashedPassword1 = CryptUtil.encode(password1);

        System.out.println("原始密码: " + password1);
        System.out.println("哈希后密码: " + hashedPassword1);

        boolean isValid1 = CryptUtil.verifyPassword(password1, hashedPassword1);
        System.out.println("验证结果(正确密码): " + isValid1); // 应该返回true

        boolean isInvalid1 = CryptUtil.verifyPassword("错误密码", hashedPassword1);
        System.out.println("验证结果(错误密码): " + isInvalid1); // 应该返回false

        // 测试用例2: 相同密码生成不同哈希
        String password2 = "AnotherPassword456";
        String hashedPassword2a = CryptUtil.encode(password2);
        String hashedPassword2b = CryptUtil.encode(password2);

        System.out.println("\n原始密码: " + password2);
        System.out.println("哈希结果1: " + hashedPassword2a);
        System.out.println("哈希结果2: " + hashedPassword2b);
        System.out.println("两次哈希值相同? " + hashedPassword2a.equals(hashedPassword2b)); // 应该返回false(因为盐值不同)

        // 但是都能验证通过
        boolean isValid2a = CryptUtil.verifyPassword(password2, hashedPassword2a);
        boolean isValid2b = CryptUtil.verifyPassword(password2, hashedPassword2b);
        System.out.println("验证结果1: " + isValid2a); // 应该返回true
        System.out.println("验证结果2: " + isValid2b); // 应该返回true

    }

}
